package com.xianyu.us.service.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xianyu.us.dao.UsUserDao;
import com.xianyu.us.pojo.entity.UsUser;

import io.lettuce.core.dynamic.annotation.CommandNaming;
/**
 * 获取用户认证和授权信息并进行疯转
 * @author J
 *
 */
@Component
public class ShiroUserRealm extends AuthorizingRealm {
	@Autowired
	private UsUserDao usUserDao;
	/**
	 * 负责授权信息的获取和封装
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		return null;
	}
	/**
	 * 负责认证信息的获取和封装
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken)token;
		String username=upToken.getUsername();
		UsUser user = usUserDao.findUserByUserName(username);
		//判定用户对象是否存在
		if(user==null)
			throw new UnknownAccountException();
		ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo
				(user, user.getPassword(), credentialsSalt, getName());
		return info;
	}
	/**
	 * 负责获取加密凭证匹配器对象
	 */
	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher hMatcher=new HashedCredentialsMatcher();
		hMatcher.setHashAlgorithmName("MD5");
		hMatcher.setHashIterations(1);
		super.setCredentialsMatcher(hMatcher);
	}
//	@Override
//	public CredentialsMatcher getCredentialsMatcher() {
//		HashedCredentialsMatcher hMatcher=new HashedCredentialsMatcher();
//		hMatcher.setHashAlgorithmName("MD5");
//		hMatcher.setHashIterations(1);
//		super.getCredentialsMatcher();
//	}

}
